<!DOCTYPE html>
<html>
<head>
  <title>我的作品</title>
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <!-- head 中 -->
  <link rel="stylesheet" th:href="@{/jquery-weui/lib/weui.css}">
  <link rel="stylesheet" th:href="@{/jquery-weui/css/jquery-weui.css}">
  <link rel="stylesheet" th:href="@{/jquery-weui/css/demos.css?t=12}">
  <style>
    html{
      height: 100%;
      overflow-y: auto;
    }
    body{
      width: 100%;
      height:100%;
      overflow-y: auto;
    }
    *{
      margin: 0;
      padding: 0;
    }
    .bd{
      width: 100%;
      height:75%;
      overflow-y: scroll;
    }
    .content {
      width: 100%; /* 内容宽度 */
      height: 100%;
      display: flex; /* 使用Flexbox布局 */
      align-items: center; /* 垂直居中 */
    }
    .wdzp{
      width:117px;
      height:90px;
      margin-left: 16px;
      margin-top: 12px;
    }
    .wdzp_div{
      width:150px;
      height:120px;
      background: url("/stamp/image/gxh_bg_slt.png");
      background-size:100%;
    }

    /*明信片 横*/
    .content_h {
      padding-left: 30px;
      width: 100%; /* 内容宽度 */
      height: 100%;
      display: flex; /* 使用Flexbox布局 */
      align-items: center; /* 垂直居中 */
      overflow: hidden;
    }
    .wdzp_h{
      width: 144px;
      height: 118px;
      margin-left: -11px;
      margin-top: -15.21px;
    }
    .wdzp_div_h{
      width:120px;
      height:90px;
      background-size:100% 100% !important;
      background-repeat: no-repeat !important;
    }

    /*明信片 竖*/
    .content_s {
      padding-left: 30px;
      width: 100%; /* 内容宽度 */
      height: 100%;
      display: flex; /* 使用Flexbox布局 */
      align-items: center; /* 垂直居中 */
      overflow: hidden;
    }
    .wdzp_s{
      width: 119px;
      height: 150px;
      margin-left: -17px;
      margin-top: -12.25px;
    }
    .wdzp_div_s{
      width:85px;
      height:128px;
      background-size:100% 100% !important;
      background-repeat: no-repeat !important;
    }
    /* 修改标题的文字大小 */
    .weui-dialog__title {
      font-size: 24px;
    }
    .weui-dialog__bd {
      font-size: 20px;
    }
    /* 修改按钮的文字大小和内边距 */
    .weui-dialog__btn {
      font-size: 20px;
      padding: 10px 20px;
    }
    /* 隐藏全屏图片的容器，初始状态下不可见 */
    #fullscreen-image {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.9);
      justify-content: center;
      align-items: center;
      z-index: 9999;
    }

    /* 全屏显示的图片样式 */
    #fullscreen-image img {
      max-width: 90%;
      max-height: 90%;
    }
    .xz_td{
      width: 80px;
      font-size: 15pt;
      text-align: center;
      white-space: nowrap;
      font-weight: bolder;
      color: #006699;
    }
    .limit-tip {
      color: #ff4d4f;
      font-size: 14px;
      text-align: center;
      padding: 10px;
      background-color: #fff8f8;
      border: 1px solid #ffe3e3;
      margin: 10px;
      border-radius: 4px;
    }
  </style>
</head>

<body>
<!-- 全屏图片的容器 -->
<div id="fullscreen-image" onclick="hideFullscreenImage()">
  <img id="fullscreen-img" src="">
</div>
<div class="bd">
  <table style="height: 55px;width: 100%;background-color: #f3f3f3;">
    <tr><td colspan="3" height="5px;"></td></tr>
    <tr>
      <td style="width: 10%;text-align: center;">&nbsp;<img src="/stamp/image/ht.png" style="width: 25px;height: 25px;" onclick="window.history.back();">&nbsp;</td>
      <td style="width: 10%;text-align: center;">&nbsp;<img src="/stamp/image/zy.png" style="width: 25px;height: 25px;" onclick="zy();">&nbsp;</td>
      <td style="width: 70%"></td>
      <td style="width: 10%;text-align: center">&nbsp;<img src="/stamp/image/sx.png" style="width: 25px;height: 25px;" onclick="window.location.reload()">&nbsp;</td>
    </tr>
  </table>

  <!-- 最大数量限制提示区域（仅数量为1时显示） -->
  <div id="limitTip" class="limit-tip" style="display: none;"></div>

  <table style="width: 99%">
    <tr>
      <td><select class="weui-select" style="font-size: 16pt;color: #006699;width: 96%;font-weight: bolder;text-align: center;height: 65px" name="post_hd" id="post_hd" onchange="on_xz(this.value)">
      </select></td>
    </tr>
  </table>
  <form id="form1" name="form1"  method="post" autocomplete="off">
    <input id="hdlx" name="hdlx" value="" type="hidden">
    <input id="zdxdsl" name="zdxdsl" value="" type="hidden">
  </form>
  <div class="weui-cells weui-cells_checkbox" id="nr">


  </div>
</div>
<div class="weui-cell">
  <div style="height: 50px;border-radius: 10px;line-height: 50px;text-align: center;color: #007b44;border: 1px solid #007b44;width: 95%;font-size:16pt;font-weight: bold" onclick="new_card();">添加制作新的作品</div>
</div>
<div class="weui-cell">
  <div class="weui-cell__hd" style="width: 69%">
    <table>
      <tr><td>已选<span id="xzsl" style="font-weight: bolder;color: #00b5f9"></span>种，合计<span id="hjsl" style="font-weight: bolder;color: #00b5f9"></span>张</td></tr>
      <tr><td>费用<span id="hjje" style="font-weight: bolder;color: #00b5f9"></span>元</td></tr>
      <tr><td style="color: #EC8B89">如有兑换码，可在付款界面直接兑换</td></tr>
    </table>
  </div>
  <div class="weui-cell__bd" style="width: 1%"></div>
  <div class="weui-cell__ft" style="width: 30%;"><a href="javascript:;" class="weui-btn weui-btn_primary" style="background-color: #007b44;color: white;width: 120px;font-size:16pt;font-weight: bold" id="qrta" onclick="kszz();">下一步</a></div>
</div>
<div style="height: 60px">&nbsp;</div>
<!-- body 最后 -->
<script type="text/javascript" th:src="@{/jquery-weui/lib/jquery-2.1.4.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jquery-weui/lib/fastclick.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jquery-weui/js/jquery-weui.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jsfiles/crypto-js.min.js?t=1}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jsfiles/com.js?t=12}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/layer/mobile/layer.js}" charset="utf-8"></script>
<script>
  $(function() {
    FastClick.attach(document.body);
  });
  var hd_id = "[[${hd_id}]]";
  var xm_id = "[[${xm_id}]]";
  var adminUrl = "[[${adminUrl}]]";
  //后端地址
  var url = "[[${serverUrl}]]/stamp/h5/api/";
  //图片显示
  var url1 = "[[${serverUrl}]]/stamp/tp/";

  function lxqh(){
    document.getElementById('post_hd').focus();
  }

  var dz = window.location.href;
  dz = dz.replace(/&/g, "$");
  function init_data(){
    $.showLoading("数据加载中...");
    var jsonData = {
      hd_id: hd_id,
      xm_id: xm_id,
      timestamp:new Date().getTime()
    };
    var sendStr = {
      data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a_h5"),localStorage.getItem("b_h5"))
    };
    $.ajax({
      type:"post",
      url:url+"get_wdzp",
      data:JSON.stringify(sendStr),
      dataType:"json",
      timeout : 10*1000, //超时时间设置，单位毫秒
      crossDomain: true,
      contentType: 'application/json;charset=UTF-8',
      headers: {
        "token": localStorage.getItem("token_h5")
      },
      beforeSend: function(request) {
        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
      },
      success:function(result){
        console.info("result:"+JSON.stringify(result));
        if (result.code==0){
          let rtn = decrypt_str(result.data,localStorage.getItem("a_h5"),localStorage.getItem("b_h5"));
          console.info("rtn:"+rtn);
          rtn = JSON.parse(rtn);
          var str="";
          //活动下拉列表
          rtn.stampHdList.forEach(function(item){
            str+="<option value=\""+item.urlId+"\">点击选择明信片或邮票：["+item.name+"]</option>";
          });
          $("#post_hd").append(str);
          $("#post_hd").val(rtn.hd_id);
          $("#hdlx").val(rtn.hd_lx);
          $("#zdxdsl").val(rtn.zdxdsl);

          // 仅当最大数量为1时显示提示
          var maxLimit = parseInt(rtn.zdxdsl) || 0;
          if (maxLimit === 1) {
            $("#limitTip").text("提示：当前活动最多选择1种产品，且数量为1").show();
          } else {
            $("#limitTip").hide(); // 其他情况不显示提示
          }

          //渲染页面数据
          str="";
          rtn.stampCardList.forEach(function(item,index){
            str+="                    <div class=\"weui-cell\" style=\"height: 200px;\" id=\"div"+item.id+"\">\n" +
                    "                        <div class=\"weui-cell__hd\" style=\"width: 5%;\">\n" +
                    "                            <label class=\"weui-cell weui-check__label\" style=\"padding: 0;\" for=\"s"+item.id+"\">\n" +
                    "                                <input class=\"weui-count__number\" id=\"je"+item.id+"\" name=\"je\" type=\"hidden\" value=\""+item.stampHd.jg+"\" />\n" +
                    "                                <div class=\"weui-cell__hd\" style=\"padding: 0px\">\n";
            if (index==0) {
              str+=" <input type=\"checkbox\" class=\"weui-check\" name=\"checkbox1\" id=\"s"+item.id+"\" value=\""+item.id+"\" onclick=\"ck_setsl("+item.id+");\" checked=\"checked\">\n" +
                      "                                            <i class=\"weui-icon-checked\"></i>";
            }else{
              str+=" <input type=\"checkbox\" class=\"weui-check\" name=\"checkbox1\" id=\"s"+item.id+"\" value=\""+item.id+"\" onclick=\"ck_setsl("+item.id+");\">\n" +
                      "                                            <i class=\"weui-icon-checked\"></i>";
            }
            str+=" </div>\n" +
                    "                            </label>\n" +
                    "                        </div>\n" +
                    "                        <div class=\"weui-cell__bd\" style=\"width: 50%;height: 200px;overflow: hidden\">";
            if (item.lx=="1"){
              str+="<div class=\"content_s\">\n" +
                      "                                    <div onclick=\"showFullscreenImage('"+url1+"wdzp_id?id="+item.id+"&token="+localStorage.getItem("token_h5")+"')\" id=\"wdzp_div_s\" style=\"background: url('"+url1+"wdzp_zst?id="+item.id+"&token="+localStorage.getItem("token_h5")+"')\" class=\"wdzp_div_s\">\n" +
                      "                                        <img id=\"wdzp_s\" src=\"/stamp/image/mxp_sb.png?t=12\" class=\"wdzp_s\">\n" +
                      "                                    </div>\n" +
                      "                                </div>";
            }else if (item.lx=="2"){
              str+="<div class=\"content_h\">\n" +
                      "                                    <div onclick=\"showFullscreenImage('"+url1+"wdzp_id?id="+item.id+"&token="+localStorage.getItem("token_h5")+"')\" id=\"wdzp_div_h\" class=\"wdzp_div_h\" style=\"background: url('"+url1+"wdzp_zst?id="+item.id+"&token="+localStorage.getItem("token_h5")+"')\">\n" +
                      "                                        <img id=\"wdzp_h\" src=\"/stamp/image/mxp_hb.png?t=12\" class=\"wdzp_h\">\n" +
                      "                                    </div>\n" +
                      "                                </div>";
            }else if (item.lx=="3"){
              str+="<div class=\"content\">\n" +
                      "                                    <div onclick=\"showFullscreenImage('"+url1+"wdzp_gxh_id?id="+item.id+"&token="+localStorage.getItem("token_h5")+"')\" id=\"wdzp_div\" class=\"wdzp_div\">\n" +
                      "                                        <img id=\"wdzp\" src=\""+url1+"wdzp_zst?id="+item.id+"&token="+localStorage.getItem("token_h5")+"\" class=\"wdzp\">\n" +
                      "                                    </div>\n" +
                      "                                </div>";
            }
            str+="                    </div>\n" +
                    "                        <div class=\"weui-cell__ft\" style=\"width: 45%;margin-right: 0\">\n" +
                    "                            <div class=\"weui-cell\">\n" +
                    "                                <div class=\"weui-cell__ft\">\n" +
                    "                                    <div class=\"weui-count\">\n" +
                    "                                        <a class=\"weui-count__btn weui-count__decrease\" onclick='jian_sl(event,"+item.id+");'></a>\n";
            if (index==0) {
              str+=" <input class=\"weui-count__number\" id=\"sl"+item.id+"\" name=\"sl\" type=\"number\" value=\"1\" />\n";
            }else{
              str+=" <input class=\"weui-count__number\" id=\"sl"+item.id+"\" name=\"sl\" type=\"number\" value=\"0\" />\n";
            }
            str+= "                                        <a class=\"weui-count__btn weui-count__increase\" onclick='jia_sl(event,"+item.id+");'></a>\n" +
                    "                                        <div style='position: absolute;right: 10px;float: right;margin-top: -25px;'><a class=\"weui-icon-delete\" onclick=\"on_del('"+item.id+"','div"+item.id+"')\"></a></div>\n" +
                    "                                    </div>\n" +
                    "                                </div>\n" +
                    "                            </div>\n" +
                    "                        </div>\n" +
                    "                    </div>";
          });
          $("#nr").html(str);

          xzsl();

        }else if (result.code==500){
          $.alert(result.msg);
        }else if (result.code==6){
          var dz = window.location.href;
          dz = dz.replace(/&/g, "$");
          if (result.code==6) window.location.href = adminUrl+"/h5/login?backurl=" + encodeURIComponent(dz);
        }
      },
      error:function(result){

      },complete:function(){
        $.hideLoading();
      }
    });
  }

  init_data();
  var MAX = 99, MIN = 0;

  // 仅当最大数量为1时，检查是否超过限制（最多选1种）
  function checkSingleLimit(checkedId) {
    var maxLimit = parseInt($("#zdxdsl").val()) || 0;
    if (maxLimit !== 1) return true; // 非1时不校验

    // 已勾选的产品数量
    var checkedCount = $("input[name='checkbox1']:checked").length;
    // 如果是勾选操作，算上当前勾选的
    if (checkedId && !$("#s"+checkedId).prop('checked')) {
      checkedCount += 1;
    }

    if (checkedCount > 1) {
      $.alert("当前活动最多选择1种产品");
      return false;
    }

    return true;
  }

  // 减少数量（仅max=1时有限制）
  function jian_sl(e,id){
    var maxLimit = parseInt($("#zdxdsl").val()) || 0;
    var $input = $(e.currentTarget).parent().find('.weui-count__number');
    var currentVal = parseInt($input.val() || "0");
    var newVal = currentVal - 1;

    // 仅当max=1时，数量不能小于1（如果勾选状态）
    if (maxLimit === 1 && $("#s"+id).prop('checked') && newVal < 1) {
      $.alert("当前活动已选产品数量必须为1");
      return;
    }

    if (newVal < MIN) newVal = MIN;

    // 数量为0时取消勾选
    if (newVal == 0) {
      $("#s"+id).prop('checked', false);
    }

    $input.val(newVal);
    xzsl();
  }

  // 增加数量（仅max=1时有限制）
  function jia_sl(e,id){
    var maxLimit = parseInt($("#zdxdsl").val()) || 0;
    var $input = $(e.currentTarget).parent().find('.weui-count__number');
    var currentVal = parseInt($input.val() || "0");
    var newVal = currentVal + 1;

    // 仅当max=1时，数量不能大于1
    if (maxLimit === 1 && newVal > 1) {
      $.alert("当前活动已选产品数量必须为1");
      return;
    }

    // 非max=1时，单品数量不超MAX
    if (maxLimit !== 1 && newVal > MAX) newVal = MAX;

    // 勾选复选框
    $("#s"+id).prop('checked', true);

    // 仅max=1时检查是否超1种
    if (maxLimit === 1 && !checkSingleLimit(id)) {
      $("#s"+id).prop('checked', false);
      return;
    }

    $input.val(newVal);
    xzsl();
  }

  // 勾选/取消勾选（仅max=1时有限制）
  function ck_setsl(id){
    var maxLimit = parseInt($("#zdxdsl").val()) || 0;
    var isChecked = $("#s"+id).prop('checked');

    // 仅当max=1时执行校验
    if (maxLimit === 1) {
      if (isChecked) {
        // 检查是否已选其他产品
        if (!checkSingleLimit(id)) {
          $("#s"+id).prop('checked', false);
          return;
        }
        // 强制数量为1
        if (parseInt($("#sl"+id).val()) !== 1) {
          $("#sl"+id).val(1);
        }
      } else {
        // 取消勾选时，数量设为0（允许取消，支持全不选）
        $("#sl"+id).val(0);
      }
    } else {
      // 非max=1时，勾选时默认数量1，取消勾选时数量0
      if (isChecked && parseInt($("#sl"+id).val()) <= 0) {
        $("#sl"+id).val(1);
      } else if (!isChecked) {
        $("#sl"+id).val(0);
      }
    }

    xzsl();
  }

  // 统计数量和金额（仅max=1时强制修正）
  function xzsl() {
    var obj = document.getElementsByName("checkbox1");
    var xzsl = 0;
    var hjsl = 0;
    var hjje = 0;
    var maxLimit = parseInt($("#zdxdsl").val()) || 0;

    for (var k in obj) {
      if (obj[k].checked) {
        xzsl++;
        var id = obj[k].value;
        var qty = parseInt($("#sl" + id).val()) || 0;
        // 仅max=1时强制数量为1
        if (maxLimit === 1) qty = 1;
        hjsl += qty;
        var price = parseFloat($("#je" + id).val()) || 0;
        hjje += price * qty;
      }
    }

    document.getElementById("xzsl").innerHTML = "&nbsp;" + xzsl.toFixed(2) + "&nbsp;";
    document.getElementById("hjsl").innerHTML = "&nbsp;" + hjsl.toFixed(2) + "&nbsp;";
    document.getElementById("hjje").innerHTML = "&nbsp;" + hjje.toFixed(2) + "&nbsp;";
  }

  // 下一步提交（仅max=1时校验）
  function kszz(){
    var xzsl = document.getElementById("xzsl").innerHTML.replaceAll("&nbsp;","");
    if (parseFloat(xzsl)<=0.00){
      $.alert("请选择需要制作的图片！");
      return;
    }

    var maxLimit = parseInt($("#zdxdsl").val()) || 0;

    // 仅当max=1时执行最终校验
    if (maxLimit === 1) {
      var checkedCount = $("input[name='checkbox1']:checked").length;
      if (checkedCount > 1) {
        $.alert("当前活动最多选择1种产品");
        return;
      }
      $("input[name='checkbox1']:checked").each(function() {
        var id = $(this).val();
        var sl = parseInt($("#sl" + id).val()) || 0;
        if (sl !== 1) {
          $.alert("当前活动已选产品数量必须为1");
          return false;
        }
      });
    }

    $.confirm("是否确定开始制作?", "信息", function() {
      psot_get_nonce_h5("gxh_card_add",url+"getnonce",onDo)
    }, function() {
      //取消操作
    });
  }

  function onDo(nonce_zhi){
    if (is_null(nonce_zhi)){
      $.alert("没有获取到操作凭证！请重试！");
      return false;
    }
    var obj = document.getElementsByName("checkbox1");
    var id = [];
    var sl = [];
    for (var k in obj){
      if (obj[k].checked) {
        id.push(obj[k].value);
        var a = "sl"+obj[k].value;
        sl.push(document.getElementById(a).value);
      }
    }
    if (id.length==0){
      alert("请选择需要制作的明细片！");
      return;
    }

    var jsonData = {
      ids:id,
      sls: sl,
      hd_id: $("#post_hd").val(),
      nonce_ms:"gxh_card_add",
      nonce_zhi:nonce_zhi,
      timestamp:new Date().getTime()
    };
    var sendStr = {
      data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a_h5"),localStorage.getItem("b_h5"))
    };
    $.showLoading("订单生成中...");
    $.ajax({
      type:"post",
      url:url+"create_order",
      data:JSON.stringify(sendStr),
      dataType:"json",
      timeout : 10*1000, //超时时间设置，单位毫秒
      crossDomain: true,
      contentType: 'application/json;charset=UTF-8',
      headers: {
        "token": localStorage.getItem("token_h5"),
      },
      beforeSend: function(request) {
        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
      },
      success:function(result){
        if (result.code==6) window.location.href = adminUrl+"/h5/login?backurl=" + encodeURIComponent(dz);
        if (result.code==0){
          let rtn = decrypt_str(result.data,localStorage.getItem("a_h5"),localStorage.getItem("b_h5"));
          parent.window.location.href=adminUrl+"/h5/card/order_info?id="+JSON.parse(rtn).id;
        }else{
          $.alert(result.msg);
        }
      },
      error:function(result){
        $.alert("发生错误！");
      },complete:function(res){
        $.hideLoading();
      }
    });
    return false;
  }

  function on_del(str,obj){
    var maxLimit = parseInt($("#zdxdsl").val()) || 0;

    $.confirm("您确定要删除图片？", "确认删除?", function() {
      $.showLoading("删除中...");
      var jsonData = {
        id: str,
        timestamp:new Date().getTime()
      };
      var sendStr = {
        data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a_h5"),localStorage.getItem("b_h5"))
      };
      $.ajax({
        type: "post",
        url: url+"wdzp_del",
        data: JSON.stringify(sendStr),
        dataType:"json",
        timeout : 10*1000,
        crossDomain: true,
        contentType: 'application/json;charset=UTF-8',
        headers: {
          "token": localStorage.getItem("token_h5")
        },
        beforeSend: function(request) {
          request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        },
        success: function (res) {
          if (res.code==0){
            $("#"+obj).remove();
            xzsl();
          }else{
            $.alert("图片删除失败!"+res.msg, "错误!");
          }
        },
        error:function(res){
          $.alert("服务器未响应！图片删除失败！", "错误");
        },
        complete:function(res){
          $.hideLoading();
        }
      });
    }, function() {
      //取消操作
    });
  }

  function new_card(){
    var hdlx=$("#hdlx").val();
    if (hdlx=="1")
      parent.location.href=adminUrl+"/h5/card/add?hd_id="+$("#post_hd").val()+"&xm_id="+encodeURIComponent(xm_id)+"";
    else if (hdlx=="2")
      parent.location.href=adminUrl+"/h5/card/gxh_add?hd_id="+$("#post_hd").val()+"&xm_id="+encodeURIComponent(xm_id)+"";
    else
      $.alert("活动丢失！");
  }

  function on_xz(str){
    window.location.href=adminUrl+"/h5/card/wdzp?hd_id="+str+"&xm_id="+encodeURIComponent(xm_id)+"";
  }

  function zy(){
    parent.location.href=adminUrl+"/h5/myhome/index?id="+encodeURIComponent(xm_id);
  }

  function showFullscreenImage(src) {
    var fullscreenImage = document.getElementById('fullscreen-image');
    var img = document.getElementById('fullscreen-img');
    img.src = src;
    fullscreenImage.style.display = 'flex';
  }

  function hideFullscreenImage() {
    var fullscreenImage = document.getElementById('fullscreen-image');
    fullscreenImage.style.display = 'none';
  }
</script>

</body>
</html>